var mongodb = require('mongodb');
var BSON = require('mongodb').pure().BSON;
/* 
if(process.env.VCAP_SERVICES){
  var env = JSON.parse(process.env.VCAP_SERVICES);
  var mongo = env['mongodb-1.8'][0].credentials;
}
else{
    var mongo = {
        "hostname":"ds039078.mongolab.com",
        "port":39078,
        "username":"admin",
        "password":"mta2013",
        "db":"activiteam"
    };
}

var generate_mongo_url = function(obj){
  obj.hostname = (obj.hostname || 'localhost');
  obj.port = (obj.port || 27017);
  obj.db = (obj.db || 'test');

  if(obj.username && obj.password){
    return "mongodb://" + obj.username + ":" + obj.password + "@" + obj.hostname + ":" + obj.port + "/" + obj.db;
  }
  else{
    return "mongodb://" + obj.hostname + ":" + obj.port + "/" + obj.db;
  }
};*/

var mongourl = process.env.MONGOLAB_DB ? process.env.MONGOLAB_DB :'mongodb://admin:mta2013@ds039078.mongolab.com:39078/activiteam';//generate_mongo_url(mongo);

/// creating a new user.
/// INPUT: the request must contain all the relevant data to create a user.
/// OUTPUT: {created: ok/error/email exists/nickname exists} (exists = there is a user with the same email in the system)
exports.createUser= function(req, res) {
    mongodb.connect(mongourl, function(err, db){
        if (err){
            res.send({"created":"error"});
            return;
        }
        else{
            var doc=req.body;
            console.log(req.body);
            //check first if the user exists:
            db.collection('users',function(err,collection){
                collection.findOne({'email':doc.email},function(err,user){
                if (user){
                    res.send({"created":"email exists"});
                    db.close();
                    return;
                }
                else{
                    collection.findOne({'nickname':doc.nickname},function(err,user){
                        if (user){
                            res.send({"created":"nickname exists"});
                            db.close();
                            return;
                        }
                        else{
                            //make object for the new user:
                            var newUser= {
                                nickname: doc.nickname,
                                email: doc.email,
                                password: doc.password,
                                fullname: doc.fullname,
                                birthDate: new Date(doc.birthDate),
                                friends: [],
                                skills: doc.skills,
                            };
                            db.collection('users', function(err,collection2) {
                                if (err) {
                                    res.send({"created":"error"});
                                    db.close();
                                    return;
                                }
                                else{
                                    collection2.insert(newUser,function(err,result){
                                        if (err){
                                            res.send({"created":"error"});
                                            db.close();
                                            return;
                                        }
                                        else{
                                            res.send({"created":"ok"});
                                            db.close();
                                            return;
                                        }
                                    });
                                }
                            });
                        }
                    });    
                }
            });
            });
        }
    });
};

/// check log in session validation
/// INPUT: {password ,email}
/// OUTPUT: {login: success/failed/error}
/// if success then the user session is updated
exports.loginUsers = function(req, res) {
    mongodb.connect(mongourl, function(err,db){
        if (err){
            res.send({"login":"error"});
            return;
        }
        //check if the system and email exists:
        db.collection('users',function(err,collection){
       if (err){
                res.send({"login":"error"});
                db.close();
                return;
                }
        else{
                collection.findOne({"email":req.body.email , "password": req.body.password},function(err,user){
                    if (err){
                        res.send({"login":"error"});
                        db.close();
                        return;
                    }
                    else if (!user){ //did not found such user
                        res.send({"login":"failed"});
                        db.close();
                        return;
                    }
                    else{ //the user was found. grant access:
                        req.session.myEmail = req.body.email;
                        req.session.myNickname = user.nickname;
                        res.send({"login":"success"});
                        db.close();
                        return;
                    }
                });
            }
        });
    });
};

///getting the data of the user:
///input: none (userid from url)
///output: the user data. different data if the user is Me (session) or other. {user: error/not found/me/other}
exports.getUser = function(req, res) {
    mongodb.connect(mongourl,function(err,db){
        db.collection('users',function(err,collection){
            if (err){
                res.send({"user":"error"});
    			db.close();
                return;
            }
            collection.findOne({"nickname":req.params.userid},function(err,user){
                db.close();
                if (err){
                    res.send({"user":"error"});
                    db.close();
                    return;	
                }
                else if (!user){
                    res.send({"user":"not found"});
                    return;
                }
                else{ //the user is found
                    if (req.session.myEmail==user.email){
                        //this is my profile:
                        delete user.password;
                        delete user._id;
                        user.user="me";
                        res.send(user);
                        return;
                    }
                    else{
                        //this is not my profile, send only relevant data:
                        user.user="other";
                        delete user.password;
                        delete user.messages;
                        delete user._id;
                        res.send(user);
                        return;
                    }
                }
            });
        });    
    });
};


//updating user's data. keeping the messages,comments...
//INPUT: req should contain: fullname,date,password,birthdate,skills.
//OUTPUT: {update: success/error/not exists/not logged}
exports.updateUser = function(req, res) {
    //check first that the session contains the email:
    if (!req.session.myEmail){
        res.send({"update":"not logged"});
        return;
    }
    else{
		//connect to the db:
		mongodb.connect(mongourl,function(err,db){
			if (err){
				res.send({"update":"error"});
				db.close();
				return;
			}
			//get users collection
			db.collection('users',function(err,collection){
				if (err)
				{
					res.send({"update":"error"});
					db.close();
					return;
				}
				var doc =req.body;
				//check first that the user exists:
				collection.findOne({'email':req.session.myEmail},function(err,user){
					if (err) {
						res.send({"update":"error"});
						db.close();
						return;
					}
					else if (!user){ //the user doesn't exists:
						res.send({"update":"not exists"});
						db.close();
						return;
					}
					else{
						//the user exists. update it:
						collection.update({"email":req.session.myEmail}, 
							{$set:
								{
									"fullname":doc.fullname,
									"password":doc.password,
									"birthDate":new Date(doc.birthDate),
									"skills":doc.skills
								}},
							{safe:true}, function(err,user){
									db.close();
									if(err){
										res.send({"update":"error"});
										return;
									} else {
										res.send({"update":"success"});
										return;
									}
								}
						);
					}
				});
			});
		});
    }
};
                        
//deleting this user
//INPUT: only the main from the session
//OUTPUT: {delete: success/error/not exists/not logged}               
exports.deleteUser = function(req, res) {
	//check first that the user is in session:
    if (!req.session.myEmail){
        res.send({"delete":"not logged"});
        return;
    }
    else{
		//connect to the db:
		mongodb.connect(mongourl,function(err,db){
			if (err){
				res.send({"delete":"error"});
				db.close();
				return;
			}
			//getting the users collection:
			db.collection('users',function(err,collection){
				if (err)
				{
					res.send({"delete":"error"});
					db.close();
					return;
				}
				//check first that the user exists:
				collection.findOne({'email':req.session.myEmail},function(err,user){
					if (err) {
						res.send({"delete":"error"});
						db.close();
						return;
					}
					else if (!user){ //the user doesn't exists:
						res.send({"delete":"not exists"});
						db.close();
						return;
					}
					else{
						//the user exists. delete it:
						collection.remove({"email":req.session.myEmail},1 
							, function(err,user){
									db.close();
									if(err){
										res.send({"delete":"error"});
										return;
									} else {
										res.send({"delete":"success"});
										return;
									}
								}
						);
					}
				});
			});
		});
    }    
};


///getting skills of a user
///input: none (userid from url)
///output: the user skills.  {skills: error/not found/success}
exports.getUserSkills = function(req, res) {
    mongodb.connect(mongourl,function(err,db){
        //get the collection
        db.collection('users',function(err,collection){
            if (err){
                res.send({"skills":"error"});
				db.close();
                return;
            }
            //find the user:
            collection.findOne({"nickname":req.params.userid},function(err,user){
                db.close();
				if (err){
					res.send({"skills":"error"});
                    return;
				}
				else if (!user){
                    res.send({"skills":"not found"});
                    return;
                }
                else{ //the user is found
                    res.send(user.skills);
                    return;
                }
            });
        });    
    });    
};

//updating user's skills. 
//INPUT: req should contain skills json.
//OUTPUT: {update: success/error/not exists/not logged}
exports.updateUserSkills = function(req, res) {
	//check first that the session contains the email:
    if (!req.session.myEmail){
        res.send({"update":"not logged"});
        return;
    }
    else{
		//connect to the db:
		mongodb.connect(mongourl,function(err,db){
			if (err){
				res.send({"update":"error"});
				db.close();
				return;
			}
			//get users collection
			db.collection('users',function(err,collection){
				if (err)
				{
					res.send({"update":"error"});
					db.close();
					return;
				}
				//check first that the user exists:
				collection.findOne({'email':req.session.myEmail},function(err,user){
					if (err) {
						res.send({"update":"error"});
						db.close();
						return;
					}
					else if (!user){ //the user doesn't exists:
						res.send({"update":"not exists"});
						db.close();
						return;
					}
					else{
						//the user exists. update its skills:
						collection.update({"email":req.session.myEmail}, 
							{$set:{"skills":req.body.skills}},
							{safe:true}, function(err,user){
									db.close();
									if(err){
										res.send({"update":"error"});
										return;
									} else {
										res.send({"update":"success"});
										return;
									}
								}
						);
					}
				});
			});
		});
    }    
};

//adding a friend to the user. 
//INPUT: req should contain the friends email {email:friendsMail}
//OUTPUT: {update: success/error/not exists/not logged}
//NOTE: not checking here that the friend exists! success even if the friend exists (addToSet)
exports.addFriend = function(req, res) {
    //check first that the session contains the email:
    if (!req.session.myEmail){
        res.send({"update":"not logged"});
        return;
    }
    else{
        //connect to the db:
        mongodb.connect(mongourl,function(err,db){
            if (err){
                res.send({"update":"error"});
                db.close();
                return;
            }
            //get users collection
            db.collection('users',function(err,collection){
                if (err)
                {
                    res.send({"update":"error"});
                    db.close();
                    return;
                }
                //check first that the user exists:
                collection.findOne({'email':req.session.myEmail},function(err,user){
                    if (err) {
                        res.send({"update":"error"});
                        db.close();
                        return;
                    }
                    else if (!user){ //the user doesn't exists:
                        res.send({"update":"not exists"});
                        db.close();
                        return;
                    }
                    else{
                        //the user exists. add his friend:
                        collection.update({"email":req.session.myEmail}, 
                            {$addToSet:{"friends":req.body.email}},
                            {safe:true}, function(err,user){
                                    db.close();
                                    if(err){
                                        res.send({"update":"error"});
                                        return;
                                    } else {
                                        res.send({"update":"success"});
                                        return;
                                    }
                                }
                        );
                    }
                });
            });
        });
    }    
};


///getting the users array of Json-friends (emails,nickname,birthDate,image_id,skills):
///input: none (userid from url)
///output: the user friends: {'friends':error/not found or the entire list}  array of (emails,nickname,fullname,birthDate,image_id,skills)
exports.getFriends = function(req, res) {
    //connecting to the database
    mongodb.connect(mongourl,function(err,db){
        //get the collection
        db.collection('users',function(err,collection){
            if (err){
                res.send({"friends":"error"});
                db.close();
                return;
            }
            //find the user:
            collection.findOne({"nickname":req.params.userid},function(err,user){
                if (err){
                    db.close();
                    res.send({"friends":"error"});
                    return;
                }
                else if (!user){ //not found this user
                    db.close();
                    res.send({"friends":"not found"});
                    return;
                }
                else{ //the user is found
                    var friendsEmailArray = user.friends;
                    //getting the friends collection:
                    collection.find({"email":{$in:friendsEmailArray}}).toArray(function(err,friends){
                        if(err){
                            res.send({"friends":"error"});
                            return;
                        }
                        var friend=null;
                        var friendsJsonArr=[];
                        for(var i=0;i<friends.length;i++){
                            friend=friends[i];
                            friendsJsonArr.push({
                                "email":friend.email,
                                "nickname":friend.nickname,
                                "fullname":friend.fullname,
                                "birthdate":friend.birthDate,
                                "image":friend.image,
                                "skills":friend.skills});
                        }
                        
                        db.close();
                        res.send({"friends":friendsJsonArr});
                        return;
                    });
                }
            });
        });    
    });      
};


//remove one of the friends
//INPUT: the session email, and email of the requested friend {email:friendsMail}
//OUTPUT: {delete: success/error/not exists/not logged}
exports.deleteFriend = function(req, res) {
    //check first that the user is in session:
    if (!req.session.myEmail){
        res.send({"delete":"not logged"});
        return;
    }
    else{
        //connect to the db:
        mongodb.connect(mongourl,function(err,db){
            if (err){
                res.send({"delete":"error"});
                db.close();
                return;
            }
            //getting the users collection:
            db.collection('users',function(err,collection){
                if (err)
                {
                    res.send({"delete":"error"});
                    db.close();
                    return;
                }
                //check first that the user exists:
                collection.findOne({'email':req.session.myEmail},function(err,user){
                    if (err) {
                        res.send({"delete":"error"});
                        db.close();
                        return;
                    }
                    else if (!user){ //the user doesn't exists:
                        res.send({"delete":"not exists"});
                        db.close();
                        return;
                    }
                    else{
                        //the user exists. delete the user:
                        collection.update({"email":req.session.myEmail},
                                {$pull:{"friends":req.body.email}},1, function(err,user){
                                    db.close();
                                    if(err){
                                        res.send({"delete":"error"});
                                        return;
                                    } else {
                                        res.send({"delete":"success"});
                                        return;
                                    }
                                }
                        );
                    }
                });
            });
        });
    }     
};


///getting the data of the user:
///input: getting the email from the session
///output: the user events. {events: error/not logged/ the entire list}
exports.readUserEvents = function(req, res) {
    //check first that the session contains the email:
    if (!req.session.myEmail){
        res.send({"events":"not logged"});
        return;
    }
    else{
      //connecting to the database
        mongodb.connect(mongourl,function(err,db){
            //get the collection
            db.collection('events',function(err,collection){
                if (err){
                    res.send({"events":"error"});
                    db.close();
                    return;
                }
                //find the events the the user is in their participants:
                collection.find({"members":req.session.myNickname}).toArray(function(err,events){
                    db.close();
                    if (err){
                        res.send({"events":"error"});
                        return;
                    }
                    else{
                        res.send({"events":events});
                        return;
                    }
                });
            });    
        });
    }
};

///getting the data of the user:
///input: getting the email from the session
///output: the user teams. {teams: error/not logged/ the entire list}
exports.readUserTeams = function(req, res) {
    //check first that the session contains the email:
    if (!req.session.myEmail){
        res.send({"teams":"not logged"});
        return;
    }
    else{
      //connecting to the database
        mongodb.connect(mongourl,function(err,db){
            //get the collection
            db.collection('teams',function(err,collection){
                if (err){
                    res.send({"teams":"error"});
                    db.close();
                    return;
                }
                //find the events the the user is in their participants:
                collection.find({"members":req.session.myNickname}).toArray(function(err,teams){
                    db.close();
                    if (err){
                        res.send({"teams":"error"});
                        return;
                    }
                    else{
                        res.send({"teams":teams});
                        return;
                    }
                });
            });    
        });
    }    
};


///getting users inbox array of messages (from,fromEmail,to,toEmail,date,text):
///input: getting the mail from the session
///output: the user inbox: {'messages':error/not logged or the entire list}  array of (emails,nickname,fullname,birthDate,image_id,skills)
exports.readUserInbox = function(req, res) {
    //check first that the session contains the email:
    if (!req.session.myEmail){
        res.send({"messages":"not logged"});
        return;
    }
    else{
        //connecting to the database
        mongodb.connect(mongourl,function(err,db){
            //get the collection:
            db.collection('messages',function(err,collection){
                if (err){
                    res.send({"messages":"error"});
                    db.close();
                    return;
                }
                //find the events the the user is in their participants:
                collection.find({"toEmail":req.session.myEmail}).sort({"date":-1}).toArray(function(err,messages){
                    db.close();
                    if (err){
                        res.send({"messages":"error"});
                        return;
                    }
                    else{
                        res.send({"messages":messages});
                        return;
                    }
                });
            });    
        });
    }      
};

///getting users outbux array of messages (from,fromEmail,to,toEmail,date,text):
///input: getting the mail from the session
///output: the user friends: {'messages':error/not logged or the entire list}  array of (emails,nickname,fullname,birthDate,image_id,skills)
exports.readUserOutbox = function(req, res) {
    //check first that the session contains the email:
    if (!req.session.myEmail){
        res.send({"messages":"not logged"});
        return;
    }
    else{
        //connecting to the database
        mongodb.connect(mongourl,function(err,db){
            //get the collection:
            db.collection('messages',function(err,collection){
                if (err){
                    res.send({"messages":"error"});
                    db.close();
                    return;
                }
                //find the events the the user is in their participants:
                collection.find({"fromEmail":req.session.myEmail}).sort({"date":-1}).toArray(function(err,messages){
                    db.close();
                    if (err){
                        res.send({"messages":"error"});
                        return;
                    }
                    else{
                        res.send({"messages":messages});
                        return;
                    }
                });
            });    
        });
    }      
};
